import Router from '../../utils/router';
import service from '../../services/conch';
import service_stote from '../../services/store';
import Record from '../../services/record-stat';
import base from '../../config/base.js';
import myindexService from '../../services/myindex.js';
import ext from '../../utils/login';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    sign_switch_open: base.static + 'conch/signswitchopen.png',
    sign_switch_close: base.static + 'conch/signswitchclose.png',
    subscribenow_img: base.static + 'conch/subscribenow.png',   
    redpag_icon: base.static + 'conch/group11.png',   
    redpag_dong: base.static + 'conch/redpag.gif',   
    icon_play: base.static + 'store/play.png',//视频标志
    icon_overseas: base.static + 'detail/haigou.png', 
    share_mask_box: true,
    friends_avatars: '',//邀请好友头像数组
    friends_conch_num: '0',//邀请好友获得的贝壳
    avatar: '',//用户头像
    sign_flag: null, //判断当天是否签到
    rest_day: '',
    sign_flag: '0',
    mask_flag: false,//弹框控制
    sign_type:'',//签到类型
    sign_add_conch:'',//签到后获得的贝壳数量
    rule_flag: 0,//活动规则开关  
    sigin_img: base.static + 'conch/background.jpg',
    signtitle_mask: base.static + 'conch/signtitle.png',
    conchclose_img: base.static + 'conch/conch.png',
    redpag_img: base.static + 'conch/redpag.gif',
    goods_img: base.static + 'conch/icon1.png',
    conchopen_img: base.static + 'conch/conchopen.gif',
    close_img: base.static + 'redenvelopes/order_suc_close.png',
    rule_img: base.static + 'conch/bitmap.png',
    mask_conchimg: base.static + 'conch/mask_conch.png',
    add_share: base.static + 'conch/addshare.png',
    arrow_img: base.static + 'detail/lin-r.png',
    laba_img:base.static + 'store/laba.png',
    sanjiao_img: base.static + 'conch/sanjiao.png',
    sold_out:base.static + 'store/csellout.png',
    mask_conchimg: base.static + 'conch/group11.png',
    tixing_img: base.static + 'conch/tixing.png',
    couponssmall_bgc: base.static + 'dailytasks/couponssmall.png',
    store_id: '',
    share_id: '',
    conch: '', //签到详情信息
    goodsList: [], //特惠商品列表
    pages: 0,
    loadBloon: true,
    endBloon: true,
    noMore: true,
    conchnum: '0',//贝壳数量
    is_sign_remind: '1',//签到开关控制
    sign_mask_flag: false,//签到蒙层控制
    noauthorize: null,
    transmit: {
      style: 'width: 550rpx; height: 94rpx;background-color: #FFA82C;font-size: 36rpx;color: #fff;text-align: center;line-height: 94rpx;position: absolute;top: 78vh;left: 50% ;margin-left: -275rpx;border-radius: 12rpx;transform: scale(0.95);animation: scaleDraw 1.5s infinite linear;',
      value: '立即签到'
    },
    scrolltop: 0,//屏幕滚动时高度
    exchange_box: false,//优惠券弹框
    coupons: {},
    coupons_flag: false,
    sevensignbox_flag:false,
    sevensignbox_time: '',
    loadsSevenSingBloean: 1,
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    let reg = /^[1-9]\d*$/;
    let user_info = wx.getStorageSync('user_info') || {lastView:{seid:''}};
    if (reg.test(options.share_id)){
      that.setData({
        share_id: options.share_id,
        store_id: user_info.lastView.seid,
        loadsSevenSingBloean: 2,        
      });
      this.getuserinfo(options.share_id);
    }else{
      that.setData({
        store_id: user_info.lastView.seid,
        loadsSevenSingBloean: 2,        
      });
    }
    //判断有没有授权
    if (user_info.info_authorize == 1) {
      that.setData({
        noauthorize: 1,
      })
    } else {
      that.setData({
        noauthorize: 2,
      })
    }
    // 签到详情
    that.signDetail();
    // 特惠商品
    that.goodsList(1);
    //买家贝壳数量
    // that.getconchnum();
    //通过邀请好友获得的贝壳和好友头像
    that.getuserheadimg();
  },
  //获取买家信息
  getuserinfo(share_id){
    let that = this;
    let param = {
      customer_id:share_id
    }
    service_stote.customerInfo(param,function(res){
      if(res && res.code == 200){
        that.setData({
          avatar: res.data.avatar
        })
      }
    })
  },
  //授权
  onGotUserInfo: function (e) {
    let that = this;
    let d = e.detail;
    if (d.errMsg == 'getUserInfo:ok') {
      ext.getUserInfo(d, b => {
        if (b) {
          that.setData({
            noauthorize: 1,
          })
          that.sign();
        }
      });
    }
  }, 
  
  //活动规则
  rule_handle(){
     this.setData({
       rule_flag : 1,
       mask_flag: true
     })
  },
  //去瓜分贝壳页面
  goshellForm(){
    this.setData({
      mask_flag: false
    })
    Router.go('shellForm');
  },
  //点击红包
  redtipstxt(){
    wx.showModal({
      title: '提示',
      content: '连签7天,下单即奖励3元现金！',
      showCancel:false
    });
    this.viewRecord('', "click", "red_envelopes");
  },
  //获取买家贝壳数
  getconchnum: function () {
    let that = this;
    let param = {};
    myindexService.getconch(param, res => {
      if (res && res.code == 1) {
        let conchnum = res.data.conch;
        // if (conchnum !== null && conchnum !== undefined && conchnum !== '' && !isNaN(Number(conchnum))) {
        //   conchnum = util.toDecimal2(util.floatAccMul(conchnum, 1));
        // }
        that.setData({
          conchnum
        });
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    }, res => {
      wx.stopPullDownRefresh();
    });
  },
  //通过邀请好友获得的贝壳和好友头像
  getuserheadimg(){
    let that = this;
    service.showrecallfriendpic({},function(res){
      if(res && res.code == 1){
        that.setData({
          friends_avatars: res.data,
        })
      }
    })
  },
  // 签到接口
  sign: function (){
    let that = this;
    that.setData({
      share_mask_box: false
    })
    let params = {
      share_id: that.data.share_id,
      store_id: that.data.store_id,
      entrance: getApp().globalData.sharerecord
    }
    if (that.data.sign_flag == 1){
      wx.showToast({
        title: '您今日已签到过了哦~',
        icon:'none'
      })
      return;
    }
    service.signconch(params, function (res) { 
      if(res && res.code == 1){
        that.setData({
          sign_type: res.data.type,
          sign_add_conch: res.data.add_conch,
          mask_flag: true,
          rule_flag: 0,
          rest_day: res.data.rest_day,
          sign_mask_flag: false,
          coupons: res.data.coupons,
          sevensignbox_time: res.data.time
        })
        if (res.data.type == 1 || res.data.type == 2) {
          that.setData({
            mask_flag: true,
          })
        } else if (res.data.type == 3) {
          that.setData({
            sevensignbox_flag: true,
            mask_flag: false,
          })
        }
       
        setTimeout(()=>{
          wx.pageScrollTo({
            scrollTop: 435,
            duration: 300
          })
        },500)
        // 签到详情
        that.signDetail();
        that.getconchnum();
      } else if (res && res.code == 0){
        //已经签到过
        wx.showToast({
          title: res.data,
          icon: 'none',
          duration: 2000
        })
      }
      that.viewRecord('',"click","qiandao_qian");
    });
  },
  // 签到详情
  signDetail: function(){
    let that = this
    let params = {}
    service.showdays(params, function (res) {
      if (res && res.code == 1) {
        that.setData({
          sign_flag: res.data.is_sign,
          conch: res.data.date,
          sharepath: res.data.share_img,
          is_sign_remind: res.data.is_sign_remind
        })
      }
      let is_sign_remind = that.data.is_sign_remind;
      let sign_flag = that.data.sign_flag;
      if (is_sign_remind == 0 && sign_flag == 0) {
        that.setData({
          sign_mask_flag: true
        })
      }
    });
  },
  //关闭弹窗
  closemask(){
    this.setData({
      mask_flag : false
    })
  },
  // 特惠商品列表
  goodsList: function (page){
    let that = this
    let params = {
      limit: 20,
      offset: page
    }
    service.getConchGoods(params, function (res) {
      if (res && res.code == 200) {
        let strarr = that.data.goodsList.concat(res.data.list);
        that.setData({
          goodsList: strarr,
          endBloon: true,
          pages: page + 1,
        })
        if (strarr.length >= res.data.count){
          that.setData({
            loadBloon: false,
            noMore: false
          })
        }
      }
    });
  },
  //去商品详情
  goDetail: function (e) {
    let that = this;
    let goods_id = e.currentTarget.dataset.good_id;
    let store_id = that.data.store_id;
    Router.go('detail', `store_id=${store_id}&goods_id=${goods_id}`, 'navigateTo');
    that.viewRecord(goods_id, "click",'');
  },
  //去贝壳明细页面
  goConchDetail(){
    let that = this;
    that.viewRecord('', "click", 'qiandao_moredetail');
    Router.go('linprice');
  },
  //关闭弹框
  close_mask_share(){
   this.setData({
     share_mask_box: false
   })
  },
  //去召唤好友页面
  gomyfirend(){
    Router.go('myfirend')
  },
  //滚动和点击屏幕记录
  viewRecord: function (goodsid, act, btnname) {
    let that = this;
    let userid = wx.getStorageSync('user_info').id
    let params = {
      name: "ltxx_buyer",
      page: 'qiandao',
      productid: goodsid,
      userid: userid,
      storeid: that.data.store_id,
      button_name: btnname,
      act: act,
      position: '',
      env: getApp().globalData.env
    }
    Record.recordstat(params, function () { });
  },
  //监听页面高度
  scrollTimer: null,
  onPageScroll: function (e) {
    let that = this;
    if (that.scrollTimer) {
      clearTimeout(that.scrollTimer)
    };
    that.scrollTimer = setTimeout(() => {
      that.setData({
        scrolltop: e.scrollTop
      })
      //商品曝光
      that.exposure(e.scrollTop)
    }, 500);
  },
  //商品曝光
  exposure: function (scroll) {
    let that = this;
    var index = 0;
    var scrolls = ''
    let promisevariable = new Promise(function (resolve, reject) {
      let s = wx.getSystemInfoSync().windowHeight;
      resolve(s);
    }).then(s => {
      wx.createSelectorQuery().selectAll('.test').boundingClientRect(function (rects) {
        if (scrolls < scroll) {
          for (let i = index, len = rects.length; i < len; i++) {
            let rect = rects[i];
            try{
              if (rect && rect.top && 0 < rect.top && rect.bottom < s) {
                that.viewRecord(rect.id, "view", '')
                index = i;
                scrolls = scroll
              }
            }catch(e){}
          }
        } else {
          for (let i = index; i >= 0; i--) {
            let rect = rects[i];
            try {
              if (rect && rect.top && 0 < rect.top && rect.bottom < s) {
                index = i;
                scrolls = scroll
              }
            } catch(e){}
          }
        }
      }).exec()
    });
  },
  //签到提醒
  //点击开关
  signReminderSwitchHandle(){
    let that = this;
    let is_sign_remind = that.data.is_sign_remind;
    if (is_sign_remind == 1){
      wx.showModal({
        title: '提示',
        content: '98%的人靠订阅提醒赚了上万贝壳！真的要关闭吗？',
        cancelText: '残忍关闭',
        confirmText: '继续提醒',
        success(res) {
          if (res.cancel) {
            service.setremind({}, function (res) {
              if (res && res.code == 1) {
                that.setData({
                  is_sign_remind: res.data,
                  sign_mask_flag:true
                })
              }
            })
          }
        }
      }) 
    } else if (is_sign_remind == 0){
      service.setremind({}, function (res) {
        if (res && res.code == 1) {
          that.setData({
            is_sign_remind: res.data
          })
        }
      })
    }
  },
  //立即订阅
  subscribenowHandle(){
    let that = this;
    service.setremind({}, function (res) {
      if (res && res.code == 1) {
        that.setData({
          is_sign_remind: res.data
        })
      }
    })
  },
  closeMaskHandle(){
    this.setData({
      mask_flag: false
    })
  },
  //关闭订阅弹窗
  closesignmask(){
    this.setData({
      sign_mask_flag:false
    })
  },
  //关闭优惠券弹框
  closemaskbox() {
    this.setData({
      exchange_box: false
    })
  },
  //点击优惠券立即使用
  gostoredetail(){
    Router.go('store')
  },
  getemit(e){
   this.setData({
     coupons_flag: e.detail.coupons_flag
   })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getconchnum();
    // 判断侧边栏签到七天签到
    let that = this;
    if (that.data.loadsSevenSingBloean != 1) {
      let loadsSevenSingBloean = that.data.loadsSevenSingBloean + 1
      that.setData({
        loadsSevenSingBloean
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },
  
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getconchnum();
    this.setData({
      cash_flag_pag: false
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let that = this;
    this.setData({
      cash_flag_pag: true
    })
    if (that.data.loadBloon && that.data.endBloon) {
      that.setData({
        endBloon: false
      })
      that.goodsList(that.data.pages);
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let that = this;
    let store_id = that.data.store_id;
    let share_id = wx.getStorageSync('user_info').id;
    let title_arr = ['每天点一点，省钱不只一点点！', '点击签到，马上领钱！', '赚大了！连续签到7天就能得3元，有福同享，点就有', '帮我点一下，就能一起领钱', '哈哈哈！签到就能领钱，你也快来吧', '天生爱分享！签到领钱你听说过吗？', '不好意思，这钱是你掉的吗？', '天上掉馅饼啦！每天签到，就能领钱', '有些钱，该领就得领','有钱不领，你是认真的吗？']
    let index = Math.floor(Math.random() * (title_arr.length));
    let paths = '';
    paths = 'pages/store/index?store_id=' + store_id + '&to=' + encodeURIComponent('/pages/conch/conch?store_id=' + store_id + '&share_id=' + share_id + '&sharerecord=conchcard' + '&user_id=' + share_id);
    return {
      title: title_arr[index],
      path: paths,
      imageUrl: 'https:' + that.data.sharepath,
    }
  }
})